package com.cobra.mapreduce.mapJoin;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class MapJoinMapper extends Mapper<LongWritable,Text, Text, NullWritable> {

    private Map<String,String> pdMap = new HashMap<>();

    private Text outK = new Text();
    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        //获取缓存文件，并把文件封装到集合中 pd.txt
        URI[] cacheFiles = context.getCacheFiles();

        FileSystem fileSystem = FileSystem.get(context.getConfiguration());
        FSDataInputStream open = fileSystem.open(new Path(cacheFiles[0]));
        //从流中读取数据
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(open, "utf-8"));
        String line;
        while (StringUtils.isNotBlank(line=bufferedReader.readLine())){
            //切割
            String[] split = line.split("\\s+");
            pdMap.put(split[0],split[1]);
        }
        IOUtils.closeStream(bufferedReader);
    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line = value.toString();
        String[] fields = line.split("\\s+");
        //获取pid
        String pname = pdMap.get(fields[1]);
        outK.set(fields[0]+"\t"+pname+"\t"+fields[2]);
        context.write(outK,NullWritable.get());
    }
}
